import * as os from 'os';
import { jsonToParamsStr } from '.';
import * as axios from 'axios';

/**
 * 获取当前机器的ip地址
 */
export function getIpLocalAddress() {
  const interfaces = os.networkInterfaces();

  for (const dev in interfaces) {
    const iface = interfaces[dev];

    for (let i = 0; i < iface.length; i++) {
      const { family, address, internal } = iface[i];

      if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
        return address;
      }
    }
  }
}

const ips = [
  'https://searchplugin.csdn.net/api/v1/ip/get',
  'https://www.ip.cn/api/index?ip&type=0',
  'https://www.ipplus360.com/getIP',
];
let ip = '';
export async function getIpAddress(index = 0) {
  const options = {
    method: 'GET',
    uri: ips[index],
    qs: '',
  };
  try {
    const res1: any = await axios.default.get(
      options.uri + '?' + jsonToParamsStr(options.qs),
      {},
    );
    const res = res1.data;
    if (res.errCode != 500 || res.code != 500) {
      if (res.ip) {
        ip = res.ip;
      } else if (res.data && res.data.ip) {
        ip = res.data.ip;
      } else if (res.data) {
        ip = res.data;
      }
      return ip;
    } else {
      if (index + 1 < ip.length) {
        getIpAddress(index + 1);
      }
    }
  } catch (error) {
    console.error('服务:' + '有问题了', error, ips[index]);
  }
}
